# utils
"""
Utility functions used in Lib-Ray.
"""

def lazytype(value, multi=False):
    """
    Lazily converts type from strings.

    Converts '2' to 2, '3.0' to 3.0, 'false' to False, and so. Anything not recognized remains a string.
    This allows us to be "lazy" in writing the data that needs to be parsed. We use this for configuration
    files and other places where the user or administrator is passing values to the program.
    
    If the multi parameter is True, then multiple values may be provided, separated by commas,
    and the returned result is always a list (even if there is only one value provided in the file).
    """     
    # Try matching lists
    if multi:
      if ',' in value:
        values = [v.strip() for v in value.split(',')]
        results = []
        for val in values:
            results.append(lazytype(val))
        return results
      else:
        return [lazytype(value)]
    
    # Simple match cases (not case sensitive)
    if value.lower() in ('none', ''): return None
    if value.lower() in ('true', 'on', 'yes', '0'): return True
    if value.lower() in ( 'false', 'off', 'no', '1'): return False

    # Try matching numbers:
    try:
      return int(value)
    except:
      pass
    try:
      return float(value)
    except:
      pass
        
    # Return a string if nothing is recognized
    return value

    
def enumstring(value, legal_values):
    """
    Allows only strings within a certain set to be used. Returns None if the string doesn't match.
    
    Used to catch input from settings where we don't want to allow non-standard input (for security
    reasons, for example).
    """
    if value.lower() in legal_values:
        return value.lower()
    else:
        return None

